package com.example.administrator.yanfoxconn.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.KLCheckListAdapter;
import com.example.administrator.yanfoxconn.adapter.KMDMTBoxAdapter;
import com.example.administrator.yanfoxconn.bean.KMDMT;
import com.example.administrator.yanfoxconn.bean.YJExceMessage;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.DateTimePickDialog30Util;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyListView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @Description 多媒体设备取用 预约时间界面
 * @Author song
 * @Date 8/2/21 5:16 PM
 */
public class KMDmtTimeActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTittle;//標題
    @BindView(R.id.btn_booked)
    Button btnBooked;//已預約列表
    @BindView(R.id.btn_up_time)
    Button btnUpTime;//提交時間
    @BindView(R.id.btn_title_right)
    Button btnUp;//結束/提交
    @BindView(R.id.tv_start_date)
    TextView tvStartDate;//开始時間
    @BindView(R.id.tv_end_date)
    TextView tvEndDate;//结束時間
    @BindView(R.id.ll_time)
    LinearLayout llTime;
    @BindView(R.id.lv_list)
    MyListView myListView;

    private String url;
    private String result;

private Boolean isFirst=true;
    private String initStartDateTime; // 初始化开始时间
    private Date selectTime = null;//所選時間
    private Date curDate = null;//當前時間
    private String curDates;//當前時間
    private String minDate ;//最小時間
    private SimpleDateFormat formatter;
    private KMDmtTimeActivity mContext = this;

    private List<KMDMT> list;
    private Map<Integer,String> checkList= new HashMap<Integer,String>();
    private KMDMTBoxAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_km_dmt_time);
        ButterKnife.bind(this);
        tvTittle.setText("預約時間");
        btnUp.setText("提交");
        btnUp.setOnClickListener(this);
        btnBooked.setOnClickListener(this);
        btnUpTime.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        tvStartDate.setOnClickListener(this);
        tvEndDate.setOnClickListener(this);

        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat formatterUse = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        SimpleDateFormat minformatter = new SimpleDateFormat("yyyy-MM-dd");
        curDate = new Date(System.currentTimeMillis());
        //获取当前时间
        initStartDateTime = formatterUse.format(curDate);
        tvStartDate.setText(formatter.format(curDate));
        tvEndDate.setText(formatter.format(curDate));
        curDates = formatter.format(curDate);
        minDate = minformatter.format(curDate);
        list = new ArrayList<KMDMT>();
        // 赋值
        for (int i = 0; i < 60; i++) {
            list.add(new KMDMT(i + "", false));
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_start_date:
                DateTimePickDialog30Util dateTimeS = new DateTimePickDialog30Util(
                        mContext, initStartDateTime);
                dateTimeS.dateTimePicKDialog(tvStartDate, minDate);
                break;
            case R.id.tv_end_date:
                DateTimePickDialog30Util dateTimeE = new DateTimePickDialog30Util(
                        mContext, initStartDateTime);
                dateTimeE.dateTimePicKDialog(tvEndDate, tvStartDate.getText().toString().split(" ")[0]);
                break;
            case R.id.btn_title_right:
                if(isFirst){

                isFirst=false;
                }else{
                    upBook();
                }
                break;
            case R.id.btn_booked:
                Intent intent = new Intent(mContext,KMDmtListActivity.class);
                intent.putExtra("from","booked");
                intent.putExtra("flag","booked");
                startActivity(intent);
                break;
            case R.id.btn_up_time:
                btnUp.setVisibility(View.VISIBLE);
                getList();
                break;
            case R.id.btn_title_left:
                if (isFirst){
                    finish();
                }else{
                    isFirst=true;
                    btnUp.setVisibility(View.VISIBLE);
                    myListView.setVisibility(View.GONE);
                    llTime.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    /**
     * 獲取所有設備
     */
    private void getList() {
        showDialog();
        url = Constants.HTTP_DMT_ALL_LIST + "?creator_id=F3416918" ;
        new Thread() {
            @Override
            public void run() {
                result = HttpUtils.queryStringForPost(url);

                Log.e("---------", "=getcarLog=fff===" + url);
                Gson gson = new Gson();
                String response = result;

                if (result != null) {
                    Log.e("---------", "result==fff===" + response);
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("result").getAsJsonArray();
                        list = new ArrayList<KMDMT>();
                        for (JsonElement type : array) {
                            KMDMT humi = gson.fromJson(type, KMDMT.class);
                            list.add(humi);
                        }
                        Message message = new Message();
                        message.what = Constants.MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    } else {
//                        isShowReturn = false;
                        Message message = new Message();
                        message.what = Constants.MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_TOAST;
                    message.obj = "網絡問題請求失敗,請重試!";
                    mHandler.sendMessage(message);
                }
                dismissDialog();
            }
        }.start();
    }
    private String ids;//获取ID用于上传
    Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.MESSAGE_TOAST://Toast彈出
                    ToastUtils.showLong(KMDmtTimeActivity.this, msg.obj.toString());
                    llTime.setVisibility(View.GONE);
                    myListView.setVisibility(View.VISIBLE);
                    // 适配
                    adapter = new KMDMTBoxAdapter(list, KMDmtTimeActivity.this,"dmt");
                    myListView.setAdapter(adapter);

                    setListViewHeightBasedOnChildren(myListView);
                    // 绑定listView的监听器
                    myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                                long arg3) {
                            // TODO Auto-generated method stub
                            // 取得ViewHolder对象
                            KMDMTBoxAdapter.ViewHolder viewHolder = (KMDMTBoxAdapter.ViewHolder) arg1.getTag();
                            // 改变CheckBox的状态
                            viewHolder.checkBox.toggle();
                            // 将CheckBox的选中状况记录下来
                            list.get(arg2).setBo(viewHolder.checkBox.isChecked());

                            // 调整选定条目
                            if (viewHolder.checkBox.isChecked() == true) {
//                    num++;
//                    pric += Integer.parseInt(list.get(arg2).getName());
                                checkList.put(arg2,list.get(arg2).getM_id());
                            } else {
//                    num--;
//                    pric -= Integer.parseInt(list.get(arg2).getName());
                                checkList.remove(arg2);
                            }
                            // 用TextView显示
//                price.setText("一共选了" + num + "件," + "价格是" + pric + "元");
                        }
                    });
                    break;
                case Constants.MESSAGE_UP://t提交提示
                    ToastUtils.showLong(KMDmtTimeActivity.this, msg.obj.toString());
                    finish();
                    break;
                case Constants.MESSAGE_NOT_NET://t提交提示
                    ToastUtils.showLong(KMDmtTimeActivity.this, R.string.net_mistake);
                    break;
            }
            super.handleMessage(msg);
        }
    };
    //提交預約設備信息
    private void upBook() {
        final String url = Constants.HTTP_DMT_BOOK_UP; //此處寫上自己的URL

        JsonObject object = new JsonObject();

        object.addProperty("type", FoxContext.getInstance().getType());
        object.addProperty("book_start_time", tvStartDate.getText().toString());
        object.addProperty("book_end_time", tvEndDate.getText().toString());
        object.addProperty("a_creator", FoxContext.getInstance().getName());

        JsonArray bookArray = new JsonArray();

        if (checkList != null && checkList.size() != 0) {
            // 键和值
            String key = null;
            String value = null;
            // 获取键值对的迭代器
            Iterator it = checkList.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                value = (String) entry.getValue();
                JsonObject jsonObject1 = new JsonObject();
                jsonObject1.addProperty("m_id", value);
                Log.e("---------", "==m_id===" + value);
                bookArray.add(jsonObject1);
            }

        } else {
        }
        object.add("book", bookArray);
        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    Log.e("---------", "==fff===" + url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();
                        Log.e("---------", "result==fff===" + result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = Constants.MESSAGE_UP;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);

                        } else {
                            Log.e("-----------", "result==" + result);
                            Message message = new Message();
                            message.what = Constants.MESSAGE_UP;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    } else {
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NOT_NET;
                        mHandler.sendMessage(message);
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    /**
     * 用於解決scrollview嵌套listview導致只顯示一條數據的問題
     * @param listView
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        KMDMTBoxAdapter listAdapter = (KMDMTBoxAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

}
